import HttpClient from '../commons/http-client';
import {
  updateService,
  updateChargeRecord,
  appendChargeRecord,
  refreshChargeRecord,
} from '../reducers/services';
import {updateCheckoutForm} from '../reducers/checkout-form';
import {LoadingStatus, updateAppState} from '../reducers/app-state';
import _ from 'lodash';
import Toast from '../components/toast';

export function loadServices(currentPlanId) {
  return async dispatch => {
    try {
      dispatch(updateAppState({loading: LoadingStatus.PENDING}));
      const servicesRep = await HttpClient.get('/web/dentistplan');
      const services = servicesRep.data.data.results;
      dispatch(updateService(services));
      dispatch(updateAppState({loading: LoadingStatus.DONE}));
    } catch (e) {
      dispatch(updateAppState({loading: LoadingStatus.ERROR}));
      throw e;
    }
  };
}

export function loadRenew(currentPlanId, serviceId) {
  return async (dispatch, getState) => {
    const {services} = getState();
    let rep = {};
    if (currentPlanId === 1) {
      // 当前免费方案
      rep = await HttpClient.get(`/web/dentistplan/${serviceId}/buy`);
    } else if (currentPlanId === serviceId) {
      rep = await HttpClient.get('/web/dentistplan/renew');
    } else if (currentPlanId < serviceId) {
      rep = await HttpClient.get(`/web/dentistplan/${serviceId}/upgrade`);
    }
    dispatch(
      updateService([
        {...services.serviceData[serviceId], renew: rep.data.data},
      ]),
    );
  };
}

export function checkout(userPlan, service, plan) {
  return async dispatch => {
    let params = {};
    const callUrl = 'https://www.molartech.com/api/v2/front_jump';
    if (userPlan.id === 1 && service.id > 1) {
      // 新购
      params = {
        type: 'buy',
        plan: service.id,
        amt: Number(service.price),
        response_url: callUrl,
      };
    } else if (userPlan.id === service.id) {
      // 续费
      params = {
        type: 'renew',
        plan: userPlan.id,
        month: plan.month,
        amt: Number(plan.amt),
        response_url: callUrl,
      };
    } else if (service.id > userPlan.id) {
      // 升级
      params = {
        type: 'upgrade',
        plan: service.id,
        amt: Number(service.price),
        response_url: callUrl,
      };
    }
    const checkoutRep = await HttpClient.post(
      '/web/dentistplan/checkout',
      params,
    );
    const {data} = checkoutRep.data;
    dispatch(updateCheckoutForm({...data.form_data, action: data.post_action}));
  };
}

export function queryResult() {
  return async (dispatch, getState) => {
    const {checkoutForm} = getState();
    const params = {
      MerchantCode: checkoutForm.MerchantCode,
      RefNo: checkoutForm.RefNo,
      Amount: checkoutForm.Amount,
    };
    const payResultRep = await HttpClient.get(
      `https://payment.ipay88.com.my/epayment/enquiry.asp?${HttpClient.encodeParams(
        params,
      )}`,
    );
  };
}

export function loadChargeRecord(page = 1) {
  return async dispatch => {
    const info = {
      page,
      page_size: 10,
      expand: 'invoice,plan',
    };
    const chargeRecordurl = `/web/chargerecord?${HttpClient.encodeParams(
      info,
    )}`;
    try {
      const chargeRecordRep = await HttpClient.get(chargeRecordurl);
      const data = _.get(chargeRecordRep, 'data.data.results', []);
      if (page > 1) {
        dispatch(appendChargeRecord(data));
      } else {
        dispatch(refreshChargeRecord(data));
      }
    } catch (e) {
      Toast.show('没有更多了');
    }
  };
}
